import express from "express";
import fs from "fs/promises";
import path from "path";
import { fileURLToPath } from "url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const jsons = express.Router();

jsons.get("/json/data", async (req, res) => {
    try {
        const filePath = path.join(__dirname, "../../../public/json/data.json");
        const rawData = await fs.readFile(filePath, 'utf-8');
        const jsonData = JSON.parse(rawData);
        res.json({ success: true, data: jsonData, message: "数据查询成功" });
    } catch (error) {
        console.log(error);
        if (error.code === 'ENOENT') {
            res.status(404).json({ success: false, message: "文件不存在" });
        } else if (error instanceof SyntaxError) {
            res.status(400).json({ success: false, message: "JSON 格式错误" });
        } else {
            res.status(500).json({ success: false, message: "服务器内部错误" });
        }
    }
});

export default jsons;